package com.sora.security;

import com.sora.enums.TokenTime;
import com.sora.exception.ApiException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Date;

@Component
public class JwtManager {

    @Value("${security.jwt.secretKey}")
    private String secretKey;

    // 短token的过期时间
//    private Duration shortExpiration = Duration.ofMinutes(20);
    // token的过期时间，设置120s后过期
    private Duration expiray = Duration.ofSeconds(120);

    // 长token的过期时间
//    private Duration longExpiration = Duration.ofDays(5);
//    private Duration longExpiration = Duration.ofSeconds(100);
    public String generate(String username) {
        Date expiration = new Date(System.currentTimeMillis() + expiray.toMillis());
//        if (time.equals(TokenTime.LONG)) {
//            expiration = new Date(System.currentTimeMillis() + longExpiration.toMillis());
//        } else if (time.equals(TokenTime.SHORT)) {
//            expiration = new Date(System.currentTimeMillis() + shortExpiration.toMillis());
//        }

        return Jwts.builder()
                .setExpiration(expiration)   // 过期时间
                .setIssuedAt(new Date())   // 签发时间
                .setSubject(username)   // 将用户名放入token
                .signWith(SignatureAlgorithm.HS512, secretKey)   // 加密
                .compact();
    }

//    public String generateLong(String username) {
//        return generate(username, TokenTime.SHORT);
//    }
//
//    public String generateShort(String username) {
//        return generate(username, TokenTime.LONG);
//    }

    public Claims parse(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }

        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            System.out.println("token解析失败");
        }
        return claims;
    }

//    public Duration getShortExpiration() {
//        return shortExpiration;
//    }
//
//    public Duration getLongExpiration() {
//        return longExpiration;
//    }
}
